<!--
 * @Date: 2022-04-21 10:30:01
 * @Author: 陶子
 * @LastEditTime: 2023-07-05 10:47:50
 * @FilePath: \jk_one-stop_cloud_mobile_v1.0\src\views\warehouseManagement\inventoryQuery\buildInStock.vue
 * @pageName: 这是--(新建入库单)--页面
-->
<template>
  <div>
    <Navbar :appTitle="appTitle" />
    <div
      class="search-content wrap-apply"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',
        paddingBottom: GLOBAL.currentEnvironment ? '0.66rem' : '',
      }"
    >
      <van-cell-group style="margin-top: 0.1rem">
        <p class="label required FormTit"><span></span>入库单号</p>
        <div class="haveUnitBox">
          <van-field
            v-model="buildForm.orderNumber"
            :maxLength="17"
            placeholder="请输入"
            @blur="checkInputValue(buildForm.orderNumber)"
          />
          <span class="btn-text" @click="genEntityCode">自动生成</span>
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>入库日期</p>
        <van-field
          is-link
          readonly
          name="picker"
          v-model="buildForm.operateTime"
          @click="timePickShow = true"
          placeholder="请选择"
        >
        </van-field>
        <div class="bottomLine" style="margin: 0.01rem 0.16rem"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>入库仓库</p>
        <van-field-select-picker
          label=""
          placeholder="请选择"
          v-model="buildForm.warehouseId"
          :columns="stockLIst"
          :option="{ label: 'text', value: 'value' }"
          @confirm="sureWare"
          @prePopShow="showBefore"
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>入库类型</p>
        <van-field-select-picker
          label=""
          placeholder="请选择"
          v-model="buildForm.operateTaskType"
          :columns="outInStockTypeList"
          :option="{ label: 'name', value: 'value' }"
        />
        <div class="bottomLine" style="margin-top: 0.01rem"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label">入库原因</p>
        <van-field
          v-model="buildForm.remark"
          rows="2"
          autosize
          label=""
          type="textarea"
          maxlength="500"
          placeholder="请输入"
          show-word-limit
        />
      </van-cell-group>
      <van-cell-group
        style="margin-top: 0.1rem"
        v-if="commodityList.length === 0"
      >
        <div class="goodTitleBox">
          <div class="label otherText">入库商品</div>
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>
      <div
        class="reportBox"
        v-for="(item, index) in commodityList"
        :key="index"
      >
        <van-cell-group style="margin-top: 0.1rem">
          <div class="goodTitleBox">
            <div class="label otherText">入库商品({{ index + 1 }})</div>
            <img
              class="buleDelete"
              @click="deleteGodd(index)"
              src="@/assets/img/delete.png"
              alt=""
            />
          </div>
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>物品编号|物品名称</p>
          <van-field-select-picker
            label=""
            placeholder="请选择"
            v-model="item.goodsId"
            :columns="stockGoodList"
            :option="{ label: 'goodText', value: 'goodsId' }"
            @confirm="sureGood($event, item)"
            @prePopShow="showBefore"
          />
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>规格</p>
          <van-field v-model="item.spec" disabled placeholder="请选择" />
          <div class="bottomLine" style="margin-top: 0.01rem"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>本次入库合格品</p>
          <van-field
            v-model="item.goodsQualifiedNum"
            @input="inputNum(item.goodsQualifiedNum, item, 'goodsQualifiedNum')"
            placeholder="请输入"
          >
            <template slot="right-icon">
              <span>
                <van-dropdown-menu active-color="#1890ff">
                  <van-dropdown-item
                    v-model="item.selectUnitQ"
                    :options="unitOpyions(item.unitList)"
                    @change="
                      (v) => changeNumUnit(v, item, 'selectUnitQ', 'rateQ', 'goodsQualifiedNum')
                    "
                  />
                </van-dropdown-menu>
              </span>
            </template>
          </van-field>
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>本次入库报废品</p>
          <van-field
            v-model="item.goodsScrapNum"
            placeholder="请输入"
            @input="inputNum(item.goodsScrapNum, item, 'goodsScrapNum')"
          >
            <template slot="right-icon">
              <span>
                <van-dropdown-menu active-color="#1890ff">
                  <van-dropdown-item
                    v-model="item.selectUnitS"
                    :options="unitOpyions(item.unitList)"
                    @change="
                      (v) => changeNumUnit(v, item, 'selectUnitS', 'rateS', 'goodsScrapNum')
                    "
                  />
                </van-dropdown-menu>
              </span>
            </template>
          </van-field>
          <div class="bottomLine"></div>
        </van-cell-group>
      </div>
      <van-cell-group>
        <div class="addBtnBox" @click="addGood">+添加</div>
      </van-cell-group>
      <van-cell-group style="margin-top: 0.1rem">
        <!-- <upload
          iconType="fj"
          @fileChange="fileChange"
          :fileIds="buildForm.dingFileInfo"
        /> -->
        <fileSelector
          iconType="fj"
          :title="'附件'"
          @fileChange="fileChange"
          :fileIds="buildForm.dingFileInfo"
        ></fileSelector>
      </van-cell-group>
      <div class="search-bottoms">
        <van-button
          type="info"
          plain
          :loading="loadingDraft"
          class="btncancel"
          loading-text="暂存中..."
          @click="submitDraft"
          >暂存</van-button
        >
        <van-button
          type="info"
          :loading="loadingSubmit"
          class="btnconfirm"
          loading-text="提交中..."
          @click="btnConfirm"
          >提交</van-button
        >
      </div>
    </div>
    <!--选择入库日期 -->
    <van-popup v-model="timePickShow" position="bottom">
      <van-datetime-picker
        @confirm="confirmPick"
        v-model="inStockTime"
        @cancel="cancelPick"
        type="date"
        title="开始时间"
        :formatter="formatter"
      />
    </van-popup>
    <goods-picker
      v-if="showGoodsPicker"
      :listUrl="listUrl"
      @getCheckedGoods="getCheckedGoods"
    ></goods-picker>
  </div>
</template>
<script>
import { getAction } from "@/api/manage";
import upload from "@/components/upload/upload";
import {
  clearNoNum,
  validateDuplicateValue,
  accAdd,
  accMul,
  accDivMin
} from "@/utils/util";
import Navbar from "@/components/navBar/navBar_right";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import {
  pmDraftSave,
  pmDraftGet,
  pmDraftDel,
  wmsWarehouseQueryByIdIsExist,
  goodsQueryByIdIsExist,
} from "@/api/mobile";
import GoodsPicker from "@/components/choiceuse/GoodsPicker";
import {
  stockListApi,
  inStockGoodApi,
  batchStockApi,
  OutInBoundTypeApi,
  findUnitListByGoodsIdSync,
} from "@/api/mobile";
import moment from "moment";
import fileSelector from "@/components/fileSelector.vue";
export default {
  name: "search",
  components: {
    VanFieldSelectPicker,
    Navbar,
    upload,
    GoodsPicker,
    fileSelector
  },
  data() {
    return {
      //商品数据
      commodityList: [
        // {
        //   goodsId: "",
        //   spec: "",
        //   assistUnit: "",
        //   goodsQualifiedNum: "",
        //   goodsScrapNum: "",
        // },
      ],
      buildForm: {
        orderNumber: "",
        operateUserId: "",
        operateTime: "",
        warehouseId: "",
        remark: "",
        complete: false,
        dingFileInfo: "",
        operateType: "1",
        operateTaskType: "",
      },
      timePickShow: false,
      stockLIst: [],
      stockGoodList: [],
      inStockTime: new Date(),
      outInStockTypeList: [],
      loadingSubmit: false,
      loadingDraft: false,
      showGoodsPicker: false,
      appTitle: this.$route.meta.title,
      listUrl: "/wms/goods/getAllGoodsBaseInfo",
    };
  },
  computed: {},
  beforeRouteLeave(to, from, next) {
    if (this.showGoodsPicker) {
      this.appTitle = this.$route.meta.title;
      this.showGoodsPicker = false;
      next(false);
    } else {
      next();
    }
  },
  mounted() {},
  created() {
    let user = localStorage.getItem("pro__Login_Userinfo");
    pmDraftGet({
      entityType: "BUILD_IN_STOCK",
    }).then((res) => {
      if (res.result && res.result.isDraft) {
        this.$nextTick(() => {
          this.checkFormInfoAsync(res.result.editable, res.result.form);
        });
      } else {
        this.buildForm.operateUserId = JSON.parse(user).value.id;
        this.buildForm.operateTime = moment(new Date()).format("YYYY-MM-DD");
      }
    });
    this.getInStockList();
    this.getStockGood();
  },
  methods: {
    changeNumUnit(v, item, key, rate, inputKey) {
      let unitList = JSON.parse(item.unitList);
      let unit = unitList.find((u) => u.id == v);
      let old_num = item[inputKey] ? accMul(item[inputKey], item[`${rate}Old`]) : '' /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
      item[key] = v;
      item[rate] = unit.conversionRate;
      item[`${rate}Old`] = unit.conversionRate;
      item[inputKey] = item[inputKey] ? accDivMin(old_num, unit.conversionRate) : '0' /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */
    },
    unitOpyions(v) {
      let list = JSON.parse(v);
      let val = list.map((item) => {
        item.value = item.id;
        item.text = item.unit;
        return item;
      });
      return val;
    },
    /* 表单中部分数据受外部影响，可能被删除或已被使用，回显暂存数据时先校验，被影响的数据直接清除或清0 */
    async checkFormInfoAsync(list, form) {
      let that = this;
      /* 校验物品是否存在 ---begin--- */
      let goodsList = list;
      for (let i = 0; i < goodsList.length; i++) {
        const item = goodsList[i];
        const goodsIsExist = await goodsQueryByIdIsExist({ id: item.goodsId });
        if (!goodsIsExist) {
          goodsList.splice(i, 1);
        } else {
          // 物品单位是否变化,如果被删就默认选定基本单位，辅助单位的转换比例在这里更新为最新转换比例
          const unitRes = await findUnitListByGoodsIdSync({
            goodsId: item.goodsId,
          });
          let selectUnitQVal = unitRes.result.find(
            (u) => u.id == item.selectUnitQ
          );
          let selectUnitSVal = unitRes.result.find(
            (u) => u.id == item.selectUnitS
          );
          item.unitList = JSON.stringify(unitRes.result);
          if (!selectUnitQVal) {
            item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id;
            item.rateQ = 1;
            item.rateQOld = 1;
            item.goodsQualifiedNum = '0';
          } else {
            item.rateQ = selectUnitQVal.conversionRate;
            item.rateQOld = selectUnitQVal.conversionRate;
          }
          if (!selectUnitSVal) {
            item.selectUnitS = unitRes.result[unitRes.result.length - 1].id;
            item.rateS = 1;
            item.rateSOld = 1;
            item.goodsScrapNum = '0';
          } else {
            item.rateS = selectUnitSVal.conversionRate;
            item.rateSOld = selectUnitSVal.conversionRate;
          }

          let goodInfo = goodsIsExist.result;
          item.spec = goodInfo.spec;
          item.assistUnit = goodInfo.assistUnit;
          item.goodsCode = goodInfo.goodsCode;
          item.goodsName = goodInfo.goodsName;
        }
      }
      that.commodityList = goodsList;
      /* 校验物品是否存在 ---end--- */

      /* 校验仓库、入库类型是否存在 ---begin--- */
      const warehouseIsExist = await wmsWarehouseQueryByIdIsExist({
        id: form.warehouseId,
      });
      if (!warehouseIsExist) {
        form.warehouseId = undefined;
      }
      OutInBoundTypeApi({ type: "I", blackTypeIds: "I8" }).then((res) => {
        let types = res.result;
        let type = types.find((item) => item.value == form.operateTaskType);
        if (!type) {
          form.operateTaskType = undefined;
        }
      });
      this.buildForm = form;
      this.buildForm.operateTime = form.operateTime
        ? moment(form.operateTime).format("YYYY-MM-DD")
        : ""; // 兼容PC端暂存
      /* 校验仓库、入库类型是否存在 ---end--- */
    },
    deleteGodd(index) {
      this.commodityList.splice(index, 1);
    },
    addGood() {
      this.showGoodsPicker = true;
      this.appTitle = "选择物品";
    },
    genEntityCode() {
      getAction("/sys/common/genEntityCode", {
        entityCode: "WMS_WAREHOUSE_OPERATE",
      }).then((res) => {
        if (res.code == 200) {
          this.buildForm.orderNumber = res.result;
        } else {
          this.buildForm.orderNumber = "";
          this.$toast(res.message);
        }
      });
    },
    fileChange(ids) {
      this.buildForm.dingFileInfo = ids;
      console.log("父组件" + ids); //你要保存的fileids
    },
    // 提交
    btnConfirm() {
      if (!this.buildForm.orderNumber) {
        this.$toast(`请输入入库单号`);
        return;
      }
      if (!this.buildForm.operateTime) {
        this.$toast(`请选择入库日期`);
        return;
      }
      if (!this.buildForm.warehouseId) {
        this.$toast(`请选择入库仓库`);
        return;
      }
      if (!this.buildForm.operateTaskType) {
        this.$toast(`请选择入库类型`);
        return;
      }
      let goodsList = [];
      for (let i = 0; i < this.commodityList.length; i++) {
        let item = this.commodityList[i];
        if (!item.goodsId) {
          this.$toast(`入库商品（${i + 1}），请选择商品`);
          return;
        }
        if (item.goodsQualifiedNum == "") {
          this.$toast(`出库商品（${i + 1}），请输入合格品数`);
          return;
        }
        if (item.goodsScrapNum == "") {
          this.$toast(`出库商品（${i + 1}），请输入报废品数`);
          return;
        }
        let goodsNum = accAdd(
          Number(item.goodsQualifiedNum),
          Number(item.goodsScrapNum)
        );
        if (goodsNum == 0) {
          this.$toast(
            `入库商品（${i + 1}），输入的合格品数与报废品数之和必须大于0`
          );
          return;
        }
        let obj = {};
        obj.goodsId = item.goodsId;
        obj.goodsQualifiedNum = accMul(item.goodsQualifiedNum, item.rateQ);
        obj.goodsScrapNum = accMul(item.goodsScrapNum, item.rateS);
        obj.goodsNum = accAdd(
          Number(obj.goodsQualifiedNum),
          Number(obj.goodsScrapNum)
        );
        goodsList.push(obj);
      }
      let params = {
        ...this.buildForm,
        goodsList,
      };
      params.operateTime = moment(params.operateTime).format("YYYY-MM-DD");
      this.loadingSubmit = true;
      this.handleSubmit(params);
    },

    handleSubmit(params) {
      batchStockApi(params).then((res) => {
        if (res.success) {
          this.$toast("新建入库成功");
          pmDraftDel({ entityType: "BUILD_IN_STOCK" }).then((res) => {});
          this.$router.go(-1);
        } else {
          this.$toast(res.message);
        }
        this.loadingSubmit = false;
      });
    },
    submitDraft() {
      let draft = {
        form: this.buildForm,
        editable: this.commodityList,
        isDraft: true,
      };
      this.loadingDraft = true;
      pmDraftSave({
        draft,
        entityType: "BUILD_IN_STOCK",
      }).then((res) => {
        if (res.code == 200) {
          this.$toast(res.message);
          this.$router.go(-1);
        } else {
          this.$toast(res.message);
        }
        this.loadingDraft = false;
      });
    },
    checkInputValue(value) {
      validateDuplicateValue(
        "wms_warehouse_operate",
        "order_number",
        value,
        "",
        (res) => {
          if (res) {
            this.buildForm.orderNumber = "";
            this.$toast(res);
          }
        }
      );
    },
    inputNum(value, item, inputKey) {
      let newNum = clearNoNum(value);
      item[inputKey] = newNum;
    },
    sureWare(itemWare) {},
    async sureGood(selectGood, item) {
      const unitRes = await findUnitListByGoodsIdSync({
        goodsId: selectGood.goodsId,
      });
      item.unitList = JSON.stringify(unitRes.result);
      item.rateQ = 1;
      item.rateS = 1;
      item.rateQOld = 1;
      item.rateSOld = 1;
      item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id;
      item.selectUnitS = unitRes.result[unitRes.result.length - 1].id;

      item.goodsQualifiedNum = 0;
      item.goodsScrapNum = 0;
      item.spec = selectGood.spec;
      item.goodsCode = selectGood.goodsCode; // 兼容PC端暂存
      item.goodsName = selectGood.goodsName; // 兼容PC端暂存
      item.assistUnit = selectGood.assistUnit;
      item.kcGoodsScrapNum = selectGood.kcGoodsScrapNum;
    },
    async getCheckedGoods(list) {
      this.showGoodsPicker = false;
      this.appTitle = this.$route.meta.title;
      let newArr = [];
      let tips = "";
      /* 当前选择商品是否已存在列表中↓ */
      this.commodityList.forEach((val) => {
        list.forEach((son) => {
          if (val.goodsId == son.id) {
            tips += `${son.goodsName},`;
            console.log("有重复", tips, son.goodsName);
            son.delete = true;
          }
        });
      });
      /* 若已存在列表中，则删除商品，不参与新增↓ */
      for (let i = 0; i < list.length; i++) {
        const good = list[i];
        const unitRes = await findUnitListByGoodsIdSync({ goodsId: good.id });
        if (!good.delete) {
          newArr.push({
            unitList: JSON.stringify(unitRes.result),
            rateQ: 1,
            rateS: 1,
            rateQOld: 1,
            rateSOld: 1,
            selectUnitQ: unitRes.result[unitRes.result.length - 1].id,
            selectUnitS: unitRes.result[unitRes.result.length - 1].id,

            goodsId: good.id,
            spec: good.spec,
            assistUnit: good.assistUnit,
            kcGoodsQualifiedNum: good.kcGoodsQualifiedNum,
            kcGoodsScrapNum: good.kcGoodsScrapNum,
            goodsCode: good.goodsCode,
            goodsName: good.goodsName,
            goodsScrapNum: "0",
            goodsQualifiedNum: "0",
          });
        }
      }
      if (newArr.length > 0) {
        this.commodityList = this.commodityList.concat(newArr);
        if (tips != "") {
          this.$toast(`物品：${tips}已存在，请直接修改数据`);
        }
      } else {
        if (tips != "") {
          this.$toast(`物品：${tips}已存在，请直接修改数据`);
        }
      }
      console.log("拿到的商品数据：", list);
    },
    showBefore(callback) {},
    getInStockList() {
      stockListApi().then((res) => {
        if (res.success) {
          this.stockLIst = res.result;
        } else {
          this.$toast(res.message);
        }
      });
      OutInBoundTypeApi({ type: "I", blackTypeIds: "I8" }).then((res) => {
        this.outInStockTypeList = res.result;
      });
    },
    getStockGood(value) {
      let obj = {
        warehouseId: value,
      };
      inStockGoodApi(obj).then((res) => {
        if (res.success) {
          this.stockGoodList = res.result;
          for (let item of this.stockGoodList) {
            item.goodText = `${item.goodsCode}|${item.goodsName}`;
          }
        } else {
          this.$toast(res.message);
        }
      });
    },

    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      if (type === "minute") {
        return val + "分";
      }
      return val;
    },
    // 确定选择时间
    confirmPick(date) {
      this.buildForm.operateTime = moment(date).format("YYYY-MM-DD");
      this.timePickShow = false;
    },
    // 取消选择时间
    cancelPick() {
      this.timePickShow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
/deep/.van-dropdown-menu__bar {
  height: auto;
  box-shadow: none;
}
.search-content {
  //  padding-bottom: 0.5rem;
  position: fixed;
  top: 0.42rem;
  width: 100%;
  height: calc(100vh - 1rem);
  background: #f5f5f5;
  overflow: scroll;
  z-index: 99;
  .formgroup {
    background: #ffffff;
    // padding: 0 0.16rem;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottoms {
    width: 100%;
    height: 0.5rem;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 0.11rem;
    box-sizing: border-box;
    font-size: 0.16rem;
    font-weight: 500;
    z-index: 9;
    .btncancel {
      flex: 1;
      background: #f6f6f6;
      // border: 0.01rem solid rgba(25, 31, 37, 0.12);
      box-sizing: border-box;
      height: 0.39rem;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 0.03rem;
      margin-right: 0.11rem;
      color: #1890ff;
    }
    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 0.39rem;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 0.03rem;
      color: #ffffff;
    }
  }
}
.bottomLine {
  height: 0.01rem;
  background-color: #f0f0f0;
  margin: 0 0.16rem;
}
.otherText {
  font-size: 0.16rem;
  font-weight: bold;
  color: #191f25;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 0.16rem;
  /deep/ .van-cell {
    padding-right: 0;
    width: 2.6rem;
  }
  /deep/ .van-field__control {
    max-width: 3rem;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
</style>
